<template>
	<div class="chat">
		<div class="community-list">
			<el-container>
				<el-main>
					<div class="chat-container" ref="chatScrollRef">
						<commonChat @deleteCollection="deleteCollection" @next="nextClick" @scrollBottom="scrollBottom" :data="chatData"></commonChat>
					</div>
					<div class="chat-send">
						
						<el-input type="textarea" autosize v-model="seachValue" placeholder="请输入您的答案,注:只有输入答案我们才会记录您的分数和面试题." @keyup.enter.native="chatSend" />
						<el-button @click="chatSend">发送</el-button>
						<el-select clearable v-model="category_id" placeholder="请选择类别搜索" @change="categoryChange">
							<el-option  v-for="item in data.categoryOption" :key="item.id" :value ="item.id" :label="item.name"></el-option>
						</el-select>
						<el-button :disable="!data.interview_status" @click="startInterview">{{!data.interview_status?'开始面试':'面试进行中...'}}</el-button>
					</div>
					<div v-show="false" ref="questionRef" v-html="data.questionData[data.question_count]?.content"></div>
					<!-- <div v-if="communityData.length === 0" class="no-data">
						<img src="../../assets/image/noData.png">
						<p>暂无内推</p>
					</div> -->
					
				</el-main>
				<el-aside>
					<div class="community-list-title">
						<span @click="tabClick(1)" :class="{'avtive':tabIndex==1}">{{data.category_name?data.category_name:'全部'}}</span>
						<span @click="tabClick(2)" :class="{'avtive':tabIndex==2}">历史</span>
					</div>
					<div class="community-list-bottom">
						<div v-if="tabIndex==1">
							<commonChatTip  :data="chatTipData"></commonChatTip>
							<div v-if="chatTipData.length === 0" class="no-data">
								<img src="../../assets/image/noData.png">
								<p>暂无面试题</p>
							</div>
						</div>
						<div v-else>
							<commonChatHistory @lookDetails="lookDetails"   :data="chatHistoryData"></commonChatHistory>
							<div v-if="chatHistoryData.length === 0" class="no-data">
								<img src="../../assets/image/noData.png">
								<p>你还没有面试过</p>
							</div>
						</div>
					</div>
				</el-aside>
			</el-container>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import {
		ref,
		onMounted,
		reactive,
		inject,
		nextTick
	} from 'vue'
	import commonChat from '../../component/commonChat.vue'
	import commonChatTip from '../../component/commonChatTip.vue'
	import commonChatHistory from '../../component/commonChatHistory.vue'
	import {similar} from '../../public/common'
	const store = inject('store') as any
	import {
		HttpInterpolateList,
		HttpNewList,
		HttpQuestionTypeList,
		HttpQuestionList,
		HttpAddQuestionColletion,
		HttpQuestionColletionList,
		HttpDeleteQuestionColletion
	} from '../../public/http'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'

	let chatData = ref([])
	let chatTipData = ref([])
	let chatHistoryData = ref([])
	let currentPage = ref(1)
	let totalPage = ref(0)
	let totalCount = ref(0)
	let seachValue = ref("")
	let isPage = ref(1)
	let category_id = ref("")
	let questionRef = ref()
	let chatScrollRef = ref()
	let tabIndex = ref(1)
	// 新闻
	let newData = ref([])
	let currentNewPage = ref(1)
	let isNewPage = ref(1)
	let data = reactive({
		categoryOption:[],
		category_name:"",
		interview_status:0,
		questionData:[],
		current_page:1,
		question_count:0,
		timeout:null,
		total_count:0
	})
	
	// 下一题
	const nextClick =  () =>{
		data.interview_status = 1
		++data.question_count
		autoSend()
		scrollBottomMain()
		
	}
	const scrollBottomMain = ()=>{
		setTimeout(async()=>{
			await nextTick()
			chatScrollRef.value.scrollTo({
				top:chatScrollRef.value.scrollHeight,
				behavior:'smooth'
			})
		},1000)
	}
	const scrollBottom = ()=>{
		if(data.timeout){
			return
		}
		data.timeout = setTimeout(()=>{
			chatScrollRef.value.scrollTo({
				top:chatScrollRef.value.scrollHeight,
				behavior:'smooth'
			})
			clearTimeout(data.timeout)
			data.timeout = null
		},500)
	}
	// 开始面试
	const startInterview =  () =>{
		if(data.interview_status){
			data.interview_status = 0
			data.question_count = 0
			ElMessage.warning("面试已结束，我们将记录您的面试内容，你可以点击右侧“历史”查看！")
			return
		}
		autoSend(1)
	}
	// 自动发送题库
	const autoSend = async (type) =>{
		if(type){
			await questionList()
		}else{
			if(data.question_count < data.total_count){
				console.log(data.question_count,(data.question_count % 20))
				if((data.question_count % 20) == 0){
					data.current_page++
					await questionList()
				}
			}else{
				data.interview_status = 0
				ElMessage.warning("题库已清零,删除历史题库可重新面试！")
				questionColletionList()
				return
			}
		}
		if(data.questionData.length > 0){
			if(type){
				ElMessage.success("面试已开始！")
				data.interview_status = 1
			}
			chatData.value.push({
				send_type:0,
				title:data.questionData[data.question_count]?.title,
				content:data.questionData[data.question_count]?.content,
				avatar:data.questionData[data.question_count]?.avatar?data.questionData[data.question_count]?.avatar:require('../../assets/image/defalut.png'),
				nickName:data.questionData[data.question_count]?.nickName
			})
			chatTipData.value.push({
				title:data.questionData[data.question_count]?.title,
			})
			scrollBottom()
		}else{
			ElMessage.warning("未找到符合类型的题库")
		}
	}
	
	// 发送问题或者答案 1答案 0问题
	const chatSend = async () => {
		if(data.interview_status == 2){
			ElMessage.warning("请点击下一题！")
			return
		}
		if(!data.interview_status){
			ElMessage.warning("你还没有开始面试！")
			return
		}
		if(!seachValue.value){
			ElMessage.warning("请输入内容！")
			return
		}
		let score = await similar(seachValue.value,questionRef.value.innerText)
		let result = await addQuestionColletion(data.questionData[data.question_count]?.id,score)
		chatData.value.push({
			send_type:1,
			score:score,
			title:seachValue.value,
			real_content:data.questionData[data.question_count]?.content,
			answer_type:0,
			avatar:store.state.userInfoX?.avatar?store.state.userInfoX?.avatar:require('../../assets/image/defalut.png')
		})
		seachValue.value = ""
		data.interview_status = 2
		scrollBottomMain()
	}
	// 查看历史详情
	const lookDetails = (item)=>{
		chatData.value.push({
			id:item.id,
			send_type:1,
			score:item.score,
			title:item.title,
			real_content:item.content,
			answer_type:0,
			question_type:1,
			create_time:item.create_time,
			avatar:item?.avatar?item?.avatar:require('../../assets/image/defalut.png'),
			nickName:item.nickName
		})
	}
	const addQuestionColletion = (id,score)=>{
		return new Promise((resolve, reject) => {
			HttpAddQuestionColletion({
				id:id,
				score:score
			}).then((res:any)=>{
				resolve(res.code)
			})
		})
	}
	// 加载问题列表
	const questionList = () =>{
		return new Promise((resolve, reject) => {
			HttpQuestionList(data.current_page,{
				key_word:"",
				category_id:category_id.value
			}).then((res:any)=>{
				if(res.code === 200){
					
					if(data.current_page == 1){
						data.questionData = res.data.questionData
					}else{
						data.questionData = data.questionData.concat(res.data.questionData)
					}
					let length = data.questionData.length
					data.total_count = res.data.total_count
					let questionData = Object.assign([],data.questionData)
					if(chatHistoryData.value.length > 0){
						questionData.forEach((v,i)=>{
							chatHistoryData.value.forEach((k)=>{
								if(k.bank_id == v.id){
									data.questionData.forEach((s,l)=>{
										if(s.id == v.id){
											data.questionData.splice(l,1)
											--data.total_count
										}
									})
									
								}
							})
							console.log(i == length - 1)
							if(i == length - 1){
								console.log(1111,data.total_count,data.questionData)
								resolve(res.data.questionData)
							}
						})
					}else{
						resolve(res.data.questionData)
					}
					
					
				}
			})
		})
	}
	// 删除问题列表
	const deleteCollection = (item)=>{
		console.log(item)
		HttpDeleteQuestionColletion({
			id:item.id
		}).then((res:any)=>{
			if(res.code === 200){
				ElMessage.success("删除成功，下次将重新面试此题！")
				questionColletionList()
				for(let i = 0;i < chatData.value.length;i++){
					if(chatData.value[i].id == item.id){
						chatData.value.splice(i,1)
						break;
					}
				}
			}else{
				ElMessage.warning(res.message)
			}
		})
	}
	// 类别列表
	const categoryMain = ()=>{
		HttpQuestionTypeList().then((res:any)=>{
			if(res.code === 200){
				data.categoryOption = res.data.questionTypeDetail
				console.log(data.categoryOption)
			}
		})
	}
	const categoryChange = (e) =>{
		data.categoryOption.forEach((v)=>{
			if(v.id == e){
				data.category_name = v.name
			}
		})
		
	}
	
	const questionColletionList = ()=>{
		HttpQuestionColletionList().then((res:any)=>{
			if(res.code === 200){
				chatHistoryData.value = res.data.questionCollectData
			}
		})
	}
	const tabClick = (index) =>{
		tabIndex.value = index
		console.log()
		if(index == 2){
			questionColletionList()
		}
	}
	onMounted(() => {
		categoryMain()
		questionColletionList()
	})
</script>

<style lang="scss">
	.chat {
		width: 100%;
		height: calc(100%);
		overflow: hidden;
		background: #efedee;
		padding: 10px 10px 0 10px;
		box-sizing: border-box;
		
		.community-input {
			width: 100%;
			height: 50px;

			.community-input-seach {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 30%;
				height: 35px;
				background-color: #ffffff;
				border-radius: 5px;
				padding: 0 10px;
			}

			input {
				width: calc(100% - 20px);
				background-color: transparent;
				border: 0;
				color: #1e1c2a;

				&::placeholder {
					color: #9195a1;
				}
			}

			img {
				width: 20px;
				height: 20px;
				cursor: pointer;

				&:hover {
					opacity: 0.6;
				}
			}
		}

		.community-list {
			width: 100%;
			height: calc(100%);
			
			.chat-container{
				width: 100%;
				max-height: calc(100% - 80px);
				overflow: auto;
			}
			.chat-send{
				width: calc(100% - 40px);
				background-color: white;
				padding: 5px 20px;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				position: relative;
				height: max-content;
				min-height: 60px;
				position: absolute;
				left: 0px;
				bottom: 10px;
				.el-textarea{
					
					width: calc(100% - 150px - 60px - 100px  - 110px);
					min-height: 40px;
					margin-right: 10px;
					textarea{
						width: 100%;
						height: 100%;
						min-height: 40px!important;
					}
				}
				.el-select{
					width: 150px;
					height: 40px;
					margin: 0  10px 0 50px;
					.select-trigger{
						width: 100%;
						height: 100%;
					}
					.el-input{
						width: 100%;
						height: 100%;
						.el-input__inner{
							width: 100%;
							height: 100%;
						}
					}
				}
				.el-button{
					width: 100px;
					height: 40px;
					&:hover{
						background-color: rgb(249, 171, 8);
						color: white;
						border: 0;
					}
				}
			}
			.el-container {
				width: 100%;
				height: 100%;
				padding: 0 0 0px 0 !important;

				.el-main {
					display: flex;
					justify-content: flex-start;
					flex-wrap: wrap;
					padding: 0 !important;
					background: transparent !important;
					position: relative;
					
				}

				.el-aside {
					width: 300px !important;
					background: white !important;
					padding: 12px;
					box-sizing: border-box;
					border-radius: 5px;

					.community-list-title {
						font-size: 15px;
						color: rgb(145, 149, 160);
						margin-right: 30px;
						cursor: pointer;
						height: 30px;
						span{
							margin-right: 20px;
							&:hover{
								color: rgb(249, 171, 8);
							}
						}
						.avtive{
							color: rgb(249, 171, 8);
						}
					}

					.community-list-bottom {
						width: 100%;
						height: calc(100% - 30px);
						overflow: auto;
					}
				}
			}
		}

		.community-page {
			width: 100%;
			height: 60px;
			background: white;
			box-shadow: 0 0 10px 0 #eee;
			display: flex;
			justify-content: space-around;
			align-items: center;
			position: relative;

			.community-page-left {
				flex: 0.3;
				display: flex;
				justify-content: flex-start;
				position: absolute;
				left: 0;

				span {
					margin-right: 30px;
					font-size: 16px;
					letter-spacing: 1px;
				}
			}

			.community-page-right {
				flex: 1;
				display: flex;
				justify-content: center;

			}
		}
		code{
			background: #f6f7f8;
			padding: 2px;
			white-space: break-spaces;
		}
		pre code{
			padding: 10px;
			box-sizing: border-box;
			background: #f6f7f8;
			color: #000;
			display: block;
			width: 90%;
			
		}
	}
</style>
